ホームに戻る
関連 :
目次 :
Dictionaryをソースとしたドロップダウンリスト
ドロップダウンリストで選択された項目をキーとして、Dictionary を検索する場合の実装例。
XAML : HogeWindow.xaml
<
Window>
(略)
<!-- ComboBox の ItemsSource を HogeItems に -->
<!-- SelectedItem を HogeItem にバインド -->
<
ComboBox ItemsSource="{Binding
Path=HogeItems,
RelativeSource={
RelativeSource Mode=FindAncestor,
AncestorType=Window}}"
SelectedItem="{Binding
Path=HogeItem,
RelativeSource={
RelativeSource Mode=FindAncestor,
AncestorType=Window}}"
Width=
"180"
HorizontalAlignment=
"Left"
Margin=
"6"/>
(略)
</
Window>
IsEditable プロパティを True に設定しない場合、入力不可のドロップダウンリストとして機能する。
コードビハインド : HogeWindow.xaml.cs
/// - = - = - = - = - = - = - = - = - = - = - = - = - = - = - = -
/// private 定数
/// - = - = - = - = - = - = - = - = - = - = - = - = - = - = - = -
// Combobox の項目 対 紐づける値
private static readonly Dictionary<string, int> C_Dic_Hoge =
new Dictionary<string, int>
{
{ "コンボボックス項目#1", 1 },
{ "コンボボックス項目#2", 2 },
:
};
/// - = - = - = - = - = - = - = - = - = - = - = - = - = - = - = -
/// public プロパティ
/// - = - = - = - = - = - = - = - = - = - = - = - = - = - = - = -
// Combobox のソース
public string[] HogeItems { get; set; }
// Combobox で選択された項目
public string HogeItem { get; set; }
/// - = - = - = - = - = - = - = - = - = - = - = - = - = - = - = -
/// コンストラクタ
/// - = - = - = - = - = - = - = - = - = - = - = - = - = - = - = -
public HogeWindow
{
// Combobox ソース初期化
HogeItems = C_Dic_Hoge.Keys.ToArray();
}
/// - = - = - = - = - = - = - = - = - = - = - = - = - = - = - = -
/// イベントハンドラ
/// - = - = - = - = - = - = - = - = - = - = - = - = - = - = - = -
private void SomeEventHandler( object sender, RoutedEventArgs e )
{
// Combobox で選択された項目から対応する値( t )を取得
// (失敗時は抜ける)
if( !C_Dic_Hoge.TryGetValue( HogeItem, out var t ) )
{
Util.MessageBoxFunc.ShowErrorMsgBox( "デバイス不正" );
return;
}
// t に応じた処理
DoSomething(t);
}
要点
- Dictionary のキーは string 、値は任意の型(デリゲートも可)
- ComboBox.ItemsSource (項目一覧 : string[]) に Dictionary のキー一覧をバインドする
- ComboBox.SelectedItem (選択された項目 : string) をキーとして Dictionary を検索する
- 検索で得られた値を用いて処理を行う